<template>
  <div class="contract_order">
    <div class="order_search_box">
      <div class="order_search">
        <el-form-item class="search_item" label="付款状态">
          <el-select class="item_input" v-model="searchObj.payStatus" placeholder="请选择" clearable>
            <el-option label="待付款" :value="1" />
            <el-option label="部分付款" :value="2" />
            <el-option label="已付款" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item class="search_item" label="下单时间">
          <el-date-picker
            class="item_input"
            v-model="searchObj.timeList"
            type="daterange"
            clearable
            range-separator=" - "
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            placeholder="请选择"
            @change="changeDate"
          />
        </el-form-item>
        <div class="search_item search_btn">
          <el-button type="primary" :icon="Search" @click="refreshList()">查询</el-button>
          <el-button type="primary" plain :icon="RefreshRight" @click="resetSearch(true)">重置</el-button>
        </div>
      </div>
      <div class="order_tab mt20">
        <el-tabs :model-value="searchObj.purchaseStatus" class="tab_nav" @tab-click="clickTab">
          <el-tab-pane v-for="item in tabList" :name="item.purchaseStatus" :key="item.purchaseStatus">
            <template #label>
              <div class="tab_label">{{ item.label }}</div>
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="order_table_search">
        <div class="search_left">
          <el-radio-group v-model="timeRange" @change="changeTimeRange">
            <el-radio-button v-for="item in radioList" :label="item.label" :value="item.value" :key="item.value" />
          </el-radio-group>
          <el-button v-if="!isChainTenant" type="primary" @click="routeToAddProject">发起订单合同</el-button>
        </div>
        <div class="search_right">
          <el-input v-model="searchObj.search" placeholder="请输入关键词" class="right_input" @change="refreshList()">
            <template #prepend>
              <el-select v-model="searchObj.searchType" placeholder="请选择" class="right_select" @change="refreshList()">
                <el-option label="订单编号" value="1" />
                <el-option label="姓名" value="2" />
                <el-option label="手机号" value="3" />
              </el-select>
            </template>
          </el-input>
          <el-button type="primary" plain :icon="RefreshRight" @click="resetSearch(false)">重置</el-button>
        </div>
      </div>
    </div>
    <div class="order_table">
      <el-row class="table_head">
        <el-col class="head_cell" :span="8"> 商品信息</el-col>
        <el-col class="head_cell" :span="2"> 订单总数</el-col>
        <el-col class="head_cell" :span="2"> 订单总件数</el-col>
        <el-col class="head_cell" :span="2"> 合同订单销售总价</el-col>
        <el-col class="head_cell" :span="2"> 付款状态</el-col>
        <el-col class="head_cell" :span="2"> 订单状态</el-col>
        <el-col class="head_cell" :span="4"> 采购金额</el-col>
        <el-col class="head_cell" :span="2"> 操作</el-col>
      </el-row>
      <div class="table_body" v-loading="loadingFlag">
        <el-empty description="暂时还没有数据" v-if="!orderData.records?.length" />
        <div class="body_row" v-for="item in orderData.records" :key="item.orderId">
          <div class="row_title">
            <div class="title_text">
              <span>订单编号：{{ item.orderNo }}</span>
              <span v-if="item.orderType === 2">|</span>
              <span v-if="item.orderType === 2" style="color: #ff9900">后补订单编号：{{ item.appendOrderNo }}</span>
              <span>订单时间：{{ item.orderTime }}</span>
            </div>
            <div class="title_text">
              <span>关联客户：{{ item.customerName }}</span>
              <span>电话：{{ item.customerMobileCode }}</span>
              <span>{{ item.commodityNum }}种({{ item.detailNum }}件)</span>
            </div>
          </div>
          <el-row class="row_content">
            <el-col :span="8" class="row_cell has_corner">
              <div class="corner_tag" v-if="item.orderType === 2">新补材料：{{ item.productCategoryNum }}</div>
              <div class="goods_cell">
                <img class="cell_image" :src="item.mainPicUrl" />
                <div class="cell_product">
                  <div class="product_name">{{ item.productAliasName }}</div>
                  <div class="product_info">{{ item.skuSpecification }}</div>
                  <div class="product_info">SKU编码:{{ item.skuCode }}</div>
                  <div class="product_info">ID：{{ item.productId }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="2" class="row_cell">{{ item.productNum }}</el-col>
            <el-col :span="2" class="row_cell">{{ item.productDetailNum }}</el-col>
            <el-col :span="2" class="row_cell"> ¥{{ item.productDetailPrice }}</el-col>
            <el-col :span="2" class="row_cell">
              <div :class="`pay-status pay-status__${item.payStatus}`">
                {{ dict.getDictName("shop_pay_status", item.payStatus) }}
              </div>
            </el-col>
            <el-col :span="2" class="row_cell">
              <div :class="`purchase-status purchase-status__${item.purchaseStatus}`">
                {{ dict.getDictName("shop_purchase_status", item.purchaseStatus) }}
              </div>
            </el-col>
            <el-col :span="4" class="row_cell">
              <div class="price_cell">
                <div>商品总价：¥{{ item.orderPrice }}</div>
                <div>应收金额：¥{{ item.actualPrice }}</div>
                <div>未收金额：¥{{ item.waitPayAmount }}</div>
                <div style="font-weight: 700">
                  <span style="color: #3d3d3d">实收金额：</span>
                  <span style="color: #ff3333">¥{{ item.payAmount }}</span>
                </div>
              </div>
            </el-col>
            <el-col :span="2" class="row_cell">
              <div class="operate_cell">
                <div>
                  <el-button type="primary" link size="small" @click="routeToDetail(item)">详情</el-button>
                </div>
                <div v-if="item.purchaseStatus === 4">
                  <el-popconfirm title="确定删除?" @confirm="deleteProduct(item)">
                    <template #reference>
                      <el-button type="primary" link size="small">删除</el-button>
                    </template>
                  </el-popconfirm>
                </div>
                <!-- <div v-if="item.orderStatus === 1">
                  <el-button type="primary" link size="small" @click="openContractModal(item, 2)"> 改为首次合同 </el-button>
                </div>
                <div v-if="item.orderStatus === 2">
                  <el-button type="primary" link size="small" @click="openContractModal(item, 3)"> 改为最终合同 </el-button>
                </div> -->
                <div v-if="item.purchaseStatus === 1 || item.purchaseStatus === 2">
                  <el-button type="primary" link size="small" @click="routeToPurchases(item)">发起采购订单</el-button>
                </div>
                <el-dropdown v-if="item.purchaseStatus === 1 || item.purchaseStatus === 2">
                  <el-button link size="small">
                    更多操作
                    <el-icon class="el-icon--right">
                      <arrow-down />
                    </el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-if="!isChainTenant" @click="openUpdatePriceModal(item)"> 修改价格 </el-dropdown-item>
                      <el-dropdown-item @click="openUpdateReceiptInfoModal(item)"> 修改地址 </el-dropdown-item>
                      <el-dropdown-item v-if="item.purchaseStatus === 1" @click="openCloseOrderModal(item)">
                        关闭交易
                      </el-dropdown-item>
                      <el-dropdown-item @click="openUpdateMarkModal(item)">添加备注</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </el-col>
          </el-row>
          <div class="row_footer">
            <div>
              收货信息：
              <span v-if="item.receivingName">{{ item.receivingName }} / </span>
              <span v-if="item.receivingMobile">{{ item.receivingMobile }} / </span>
              <span v-if="item.receivingAreaDetail || item.receivingAddress">
                {{ item.receivingAreaDetail }} {{ item.receivingAddress }}
              </span>
            </div>
            <!-- <div style="display: flex">订单备注：<RemarkEditor v-model="item.remark" :isEdit="false" /></div> -->
          </div>
        </div>
      </div>
    </div>
    <div class="order_page">
      <el-pagination
        v-model:current-page="searchObj.page"
        v-model:page-size="searchObj.size"
        :page-sizes="[10, 20, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="Number(orderData.total)"
        @change="refreshList(searchObj.page)"
      />
    </div>

    <change-Contract
      :dialogVisible="changeContractFlag"
      :status="currProduct.contractStatus"
      @ok="updateContract"
      @close="changeContractFlag = false"
    />

    <CloseOrderDialog v-if="closeOrderFlag" v-model="closeOrderFlag" :orderDetail="currProduct" @success="successHandle" />
    <UpdateMarkDialog v-if="updateMarkFlag" v-model="updateMarkFlag" :orderDetail="currProduct" @success="successHandle" />
    <UpdatePriceDialog v-if="updatePriceFlag" v-model="updatePriceFlag" :orderDetail="currProduct" @success="successHandle" />
    <updateReceiptInfoDialog
      v-if="updateReceiptInfoFlag"
      v-model="updateReceiptInfoFlag"
      :orderDetail="currProduct"
      @success="successHandle"
    />
  </div>
</template>

<script setup>
import { nextTick, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { Search, RefreshRight } from "@element-plus/icons-vue";
import { delOrder, getOrderList, updateOrderStatus } from "@/apis/order";
import moment from "moment";
import useCodeArrStore from "@/store/modules/select";
import { ElMessage } from "element-plus";
import changeContract from "../components/changeContract.vue";
import UpdateMarkDialog from "./components/updateMarkDialog.vue";
import UpdatePriceDialog from "./components/updatePriceListDialog.vue";
import updateReceiptInfoDialog from "./components/updateReceiptInfoDialog.vue";
import CloseOrderDialog from "./components/closeOrderDialog.vue";
// import RemarkEditor from "@/components/RemarkEditor";
const isChainTenant = JSON.parse(localStorage.getItem("userinfo"))?.isChainTenant; //判断是否是加盟商

const tabList = [
  { label: "待采购", purchaseStatus: 1 },
  { label: "部分采购", purchaseStatus: 2 },
  { label: "已采购", purchaseStatus: 3 },
  { label: "已撤销", purchaseStatus: 4 },
  { label: "全部", purchaseStatus: "" }
];

const radioList = [
  { label: "今日", value: 0 },
  { label: "昨天", value: 1 },
  { label: "近7天", value: 7 },
  { label: "近30天", value: 30 }
];

const route = useRoute();
const router = useRouter();
const purchaseStatus = Number(route.query.purchaseStatus) || 1;
const dict = useCodeArrStore();

const searchObj = ref({
  page: 1,
  size: 20,
  purchaseStatus
});
const timeRange = ref();
const orderData = ref({ total: 0 });
const currProduct = ref({});
const loadingFlag = ref(false);
const changeContractFlag = ref(false);
const updateMarkFlag = ref(false);
const updatePriceFlag = ref(false);
const updateReceiptInfoFlag = ref(false);
const closeOrderFlag = ref(false);

const changeDate = item => {
  searchObj.value.startDate = item[0];
  searchObj.value.endDate = item[1];
};

const changeTimeRange = item => {
  searchObj.value.timeList = searchObj.value.timeList || [];

  const currentData = moment();

  searchObj.value.timeList[1] = currentData.format("YYYY-MM-DD");
  searchObj.value.endDate = currentData.format("YYYY-MM-DD");

  currentData.subtract(item, "days");

  searchObj.value.timeList[0] = currentData.format("YYYY-MM-DD");
  searchObj.value.startDate = currentData.format("YYYY-MM-DD");

  refreshList();
};

const clickTab = ({ paneName }) => {
  searchObj.value.purchaseStatus = paneName;
  refreshList();
};

const deleteProduct = async ({ orderId }) => {
  await delOrder({ orderId });
  successHandle("订单删除成功");
};

// const openContractModal = (item, contractStatus) => {
//   changeContractFlag.value = true;
//   currProduct.value = { ...item, contractStatus };
// };

const updateContract = async contractStatus => {
  await updateOrderStatus({
    orderStatus: contractStatus,
    orderId: currProduct.value.orderId
  });
  successHandle("订单修改成功");
  changeContractFlag.value = false;
};

const openUpdateMarkModal = item => {
  currProduct.value = item;
  updateMarkFlag.value = true;
};

const openUpdatePriceModal = item => {
  currProduct.value = item;
  updatePriceFlag.value = true;
};

const openUpdateReceiptInfoModal = item => {
  let ids = [];
  if (item.receivingAreaIds) {
    ids = item.receivingAreaIds.split(",");
  }
  currProduct.value = {
    ...item,
    receivingAreaIds: ids
  };
  updateReceiptInfoFlag.value = true;
};

const openCloseOrderModal = item => {
  if (item.pureProcurementOrder === 1) {
    ElMessage.error("请在商城-预算报价进行关闭交易操作！");
    return;
  }
  currProduct.value = item;
  closeOrderFlag.value = true;
};

const routeToAddProject = () => {
  router.push({
    path: "/oder/add"
  });
};

const routeToDetail = ({ orderId }) => {
  router.push({
    path: "/oder/detail",
    query: { orderId }
  });
};

const routeToPurchases = ({ orderId }) => {
  router.push({
    path: "/oder/detail",
    query: { orderId }
  });
};

const resetSearch = flag => {
  if (flag) {
    delete searchObj.value.timeList;
    delete searchObj.value.startDate;
    delete searchObj.value.endData;
    delete searchObj.value.payStatus;
  } else {
    delete searchObj.value.searchType;
    delete searchObj.value.search;
  }
  refreshList();
};

const refreshList = async page => {
  loadingFlag.value = true;
  searchObj.value.page = page || 1;
  try {
    const { data } = await getOrderList(searchObj.value);
    orderData.value = {};
    nextTick(() => {
      orderData.value = data;
    });
  } finally {
    loadingFlag.value = false;
  }
};

const successHandle = msg => {
  ElMessage({ message: msg, type: "success" });
  refreshList(searchObj.value.page);
};

(() => {
  refreshList();
})();
</script>
<style lang="scss">
.contract_order {
  display: grid;
  grid-template-columns: 100%;
  grid-template-rows: auto 1fr auto;
  box-sizing: border-box;
  height: 100%;
  padding: 20px;

  .order_search_box {
    .order_search {
      display: flex;
      flex-wrap: wrap;
      gap: 60px;
      padding: 20px;
      background: #f6f8fa;

      .search_item {
        width: 320px;
        margin: 0;

        .item_input {
          background: white !important;

          .el-select__wrapper {
            background: white;
          }
        }
      }

      .search_btn {
        flex: 1;
        display: flex;
        justify-content: flex-end;
      }
    }

    .order_tab {
      .tab_label {
        padding: 0 16px;
      }

      .el-tabs__item {
        padding: 0;
        width: calc(100% + 32px);
      }
    }

    .order_table_search {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .search_left {
        display: flex;
        align-items: center;
        gap: 10px;

        .el-radio-button__inner {
          width: 90px;
        }

        .is-active {
          .el-radio-button__inner {
            color: #007dff !important;
            background: none !important;
          }
        }
      }

      .search_right {
        display: flex;
        gap: 10px;
        align-items: center;

        .right_input {
          width: 300px;
          box-shadow: none !important;

          .el-input-group__prepend {
            width: 95px;
            background: white;
            padding: 0;
            box-shadow: none !important;

            .right_select {
              width: 100px;
              border: 1px solid #dcdfe6;
              border-radius: 4px 0 0 4px;

              .el-select__wrapper {
                box-shadow: none !important;
              }
            }
          }

          .el-input__wrapper {
            background: white;
            border: 1px solid #dcdfe6;
            border-radius: 0 4px 4px 0;
            box-shadow: none !important;
          }
        }
      }
    }
  }

  .order_table {
    padding: 10px 0;
    overflow: hidden;

    .table_head {
      background: #f2f6fc;

      .head_cell {
        padding: 10px 0;
        text-align: center;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }

    .table_body {
      box-sizing: border-box;
      height: calc(100% - 37px);
      padding: 10px 0;
      overflow: auto;

      .body_row {
        display: grid;
        grid-template-columns: repeat(100%, 3);
        gap: 1px 0;
        background: #e1e6ed;
        border: 1px solid #e1e6ed;
        margin-bottom: 10px;

        .row_title {
          display: flex;
          justify-content: space-between;
          background: #f5f7fa;
          padding: 10px 20px;

          .title_text {
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 12px;
            color: #3d3d3d;
          }
        }

        .row_cell {
          display: flex;
          align-items: center;
          padding: 10px 12px;
          color: #4e5969;
          line-height: 22px;
          background: white;
          outline: 1px solid #e1e6ed;
        }

        .has_corner {
          display: block;
          padding: 0;

          .corner_tag {
            display: inline-block;
            background: #409eff;
            color: white;
            border-radius: 0px 0px 5px 0px;
            font-size: 12px;
            padding: 0 5px;
          }
        }

        .goods_cell {
          box-sizing: border-box;
          display: grid;
          grid-template-columns: 80px calc(100% - 100px);
          gap: 20px;
          padding: 10px;
          width: 100%;

          .cell_image {
            width: 80px;
            height: 80px;
            border-radius: 4px;
          }

          .cell_product {
            .product_name {
              color: #3d3d3d;
              font-weight: 700;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              line-height: 24px;
            }

            .product_info {
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              font-size: 12px;
              color: #86909c;
              line-height: 20px;
            }
          }
        }

        .price_cell {
          margin: 0 auto;
        }

        .operate_cell {
          display: block;
          margin: 0 auto;
        }

        .row_footer {
          color: #4e5969;
          padding: 10px 20px;
          background: white;
        }
      }
    }
  }

  .order_page {
    display: flex;
    justify-content: end;
  }

  .pay-status {
    padding: 0 10px;
    border-radius: 2px;
    white-space: nowrap;

    &__1 {
      color: #ff9900;
      background: #fff0d9;
    }

    &__2 {
      color: #14c85c;
      background: #e3f9e9;
    }

    &__3 {
      color: #007dff;
      background: #d9edff;
    }
  }

  .purchase-status {
    &__1 {
      color: #ff9900;
    }

    &__2 {
      color: #409eff;
    }

    &__3 {
      color: #0bcd45;
    }

    &__4 {
      color: #ff3333;
    }
  }
}
</style>
